import i18n from "i18next";
import i18next from "i18next";
import { IResourcesKey } from './JsonKey';

export const tk = IResourcesKey;
const defaultNS = "translation";

enum supportLanguages {
    en = "en",
    cn = "cn",
    kr = "kr",
    ja = "ja"
};

export default async function initI18n(): Promise<void> {
    const language = getCurrentLanguage();
    const data = await getI18nResources();
    await i18n.init({
        lng: language,
        ns: [],
        fallbackLng: language,
        defaultNS: defaultNS,
        resources: {
            [language]: {
                [defaultNS]: data,
            },
        },
        parseMissingKeyHandler: (key: string) => key,
        react: {
            useSuspense: false,
        },
    });
}

async function getI18nResources(): Promise<any> {
    const lang = getCurrentLanguage();
    function getMolderRes() {
        return import(`./resources/${LanguageTool.convertToSupportLanguage(lang)}.ts`);
    }
    return await getMolderRes().then(res => res.default);
}

function getCurrentLanguage(): string {
    let language: string = supportLanguages.cn;
    const searchLang = new URLSearchParams(window.location.search).get('lang') || '';
    if (searchLang) {
        language = searchLang;
    }
    return language;
};

class LanguageTool {
    static convertToSupportLanguage: (lang: string) => supportLanguages = (lang: string) => {
        if (supportLanguages[lang as supportLanguages]) {
            return supportLanguages[lang as supportLanguages];
        }
        return supportLanguages.en;
    }
    static isEn = () => getCurrentLanguage() === supportLanguages.en;
};
export const useITranslation = (_param = "") => {
    return {
        t: (tk: string, args?: any) => {
            return i18next.t(tk, args) as string;
        }
    }
};

export const RS = new Proxy(IResourcesKey, {
    get(_target, p, _receiver) {
        return i18next.t((IResourcesKey as any)[p]);
    },
    set: () => false,
});